library(scales)
library(dplyr)
library(tidyr)
library(ggplot2)

# Prepare the data
data_cut <- data %>%
  filter(year %in% c(2021, 2024)) %>%    
  filter(group == "all") %>%
  mutate(
    ts_savother = ts_anysavings - ifelse(is.na(ts_savfor_mm), 0, ts_savfor_mm) - ts_savfor_fi_MErank - ts_savsemfor_MErank,
    saved_fi_only = ts_savfor_fi_MErank,
    saved_mm_only = ts_savfor_mm_MErank,
    saved_both = (ts_savfor_mm + ts_savfor_fi - ts_savfor_fi_mm),
    saved_semi_other = ts_savsemfor + ts_savother
  )

plot_sav <- data_cut %>% 
  filter(countrynewwb == "LMIC") %>% 
  select(countrynewwb, year, saved_fi_only, saved_mm_only, saved_both, saved_semi_other, ts_anysavings) %>%
  gather(group, value, saved_fi_only, saved_mm_only, saved_both, saved_semi_other) %>%
  mutate(
    total = ts_anysavings * 100,
    value = value * 100
  ) %>%
  filter(!is.na(value))

plot_sav$countrynewwb <- ifelse(
  plot_sav$countrynewwb == "LMIC", 
  "Low- and middle-income economies", 
  plot_sav$countrynewwb
)

max_val <- max(plot_sav$total, na.rm = TRUE) + 7
if (!is.finite(max_val)) max_val <- 250
if (max_val > 100) max_val <- 250

length_unique_countries <- plot_sav %>%
  summarise(unique_countries = n_distinct(countrynewwb)) %>%
  pull(unique_countries)

if (length_unique_countries < 8) {
  width_num <- 8
  height_num <- 4
} else {
  width_num <- 8 + floor((length_unique_countries - 1) / 4) * 2
  height_num <- 4 + floor((length_unique_countries - 1) / 4)
}

# Final plot with black outline
p <- ggplot(plot_sav) +
  geom_bar(aes(
    x = factor(year),
    y = value,
    fill = factor(group, levels = rev(c(
      "saved_fi_only", "saved_both", "saved_mm_only", "saved_semi_other"
    )))),
    stat = "identity",
    position = "stack",
    width = 0.75,
    color = "black",   
    size = 0.75        
  ) +
  scale_fill_manual(
    values = c(
      "saved_fi_only" = "#5696D0", 
      "saved_both" = "#8066AB",
      "saved_mm_only" = "#D12891",
      "saved_semi_other" = "#C2C0C0"
    ),
    breaks = c(
      "saved_fi_only", 
      "saved_both", 
      "saved_mm_only", 
      "saved_semi_other"
    ),
    labels = c(
      "Saved formally at a bank or similar financial institution only",
      "Saved formally at a bank or similar financial institution and using a mobile money account",
      "Saved formally using a mobile money account only",
      "Saved semiformally or using other methods only"
    )
  ) +
  scale_y_continuous(
    limits = c(0, 80),
    breaks = seq(0, 80, by = 20)
  ) +
  facet_grid(. ~ countrynewwb,
             scales = "free",
             space = "free",
             switch = "both",
             labeller = label_wrap_gen(width = 9, multi_line = TRUE)) +
  theme(
    strip.placement = "outside",
    strip.text.y.left = element_text(angle = 0),
    strip.text.x = element_text(size = 16, family = "Nunito Sans", colour = "black", angle = 0),
    panel.background = element_blank(),
    strip.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    legend.title = element_blank(),
    legend.position = "bottom",
    legend.justification = "center",
    legend.box.margin = margin(0, 0, 20, 0),
    axis.text.x = element_text(size = 14, family = "Nunito Sans", color = "black", margin = margin(t = 5)),
    axis.text.y = element_text(size = 14, family = "Nunito Sans", color = "black"),
    axis.ticks.x = element_blank(),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    plot.subtitle = element_text(size = 18, color = "black", family = "Nunito Sans"),
    plot.title = element_text(hjust = 0, size = 20, color = "black", family = "Nunito Sans", face = "bold"),
    plot.title.position = "plot",
    legend.text = element_text(hjust = 0, size = 16, color = "black", family = "Nunito Sans"),
    legend.text.align = 0,
    plot.caption.position = "plot",
    plot.caption = element_text(hjust = 0, size = 14, family = "Nunito Sans", color = "black")
  ) +
  guides(fill = guide_legend(ncol = 1)) +
  labs(
    subtitle = "Adults saving any money in the past years (%), 2021-2024",
    title = "More adults are using mobile money accounts to save",
    caption = "\nSource: Global Findex Database 2025\n\nNote: People may save in multiple ways, but categories in the figure are constructed to be mutually exclusive. 'Saved formally' includes all adults who saved any\nmoney formally. 'Saved semiformally' includes all adults who saved any money semiformally but not formally."
  )

# Display plot


# Save plot
ggsave(
  filename = file.path(folder_path, "3.1.3.4.png"),
  plot = p,
  width = 14,
  height = 7,
  units = "in",
  device = 'png',
  dpi = 120
)
